import { _decorator, Component, director, Node, sys, v2, v3 } from 'cc';
import * as cc from 'cc';

export interface ISerializable {
    serialize(): any; // 返回组件需要保存的数据
    deserialize(data: any): void; // 根据数据还原组件状态
}

export function saveScene() {
    const scene = cc.director.getScene();
    const nodes = scene.children;

    const savedData = nodes.map((node) => {
        const nodeData = {
            name: node.name,
            position: { x: node.position.x, y: node.position.y },
            rotation: node.rotation,
            scale: { x: node.scale.x, y: node.scale.y },
            components: [],
        };

        // 遍历节点上的所有组件
        const components = node.getComponents(Component);
        components.forEach((comp) => {
            const ser: ISerializable = comp as any;
            if (ser.serialize) {
                // 如果组件实现了 ISerializable 接口
                const compData = {
                    type: comp.constructor.name, // 组件类型
                    data: ser.serialize(), // 组件数据
                };
                nodeData.components.push(compData);
            }
        });

        return nodeData;
    });

    // 保存到本地存储
    sys.localStorage.setItem('savedScene', JSON.stringify(savedData));
    console.log('Scene saved.');
}

export function loadScene() {
    const savedData = sys.localStorage.getItem('savedScene');
    if (!savedData) {
        console.log('No saved scene found.');
        return;
    }

    const sceneData = JSON.parse(savedData);
    const scene = director.getScene();

    sceneData.forEach((nodeData) => {
        // 创建节点
        const node = new Node(nodeData.name);
        node.position = v3(nodeData.position.x, nodeData.position.y);
        node.rotation = nodeData.rotation;
        node.scale = v3(nodeData.scale.x, nodeData.scale.y, 1);

        // 还原组件
        nodeData.components.forEach((compData) => {
            const comp = node.addComponent(globalThis[compData.type]); // 动态添加组件
            const ser: ISerializable = comp as any;
            if (ser.deserialize) {
                ser.deserialize(compData.data); // 还原组件数据
            }
        });
        scene.removeAllChildren();
        // 将节点添加到场景中
        scene.addChild(node);
    });
}
